package Day7;

import org.junit.Test;

import java.util.Arrays;
import java.util.Comparator;

public class TestUserSort {

    @Test
    public void defaultSort() {
        User[] users = initData();
        //调用Arrays.sort对User类型的数组进行排序,默认根据Comparable提供的规则进行排序
        Arrays.sort(users);
        System.out.println(Arrays.toString(users));
    }

    public User[] initData() {
        User[] users = new User[5];
        users[0] = new User(1, "LL");
        users[1] = new User(2, "李四");
        users[2] = new User(3, "王五");
        users[3] = new User(4, "赵六");
        users[4] = new User(5, "小七");

        return users;
    }


    @Test
    public void customSort() {
        User[] users = initData();
        // 使用 Comparator 进行自定义排序
        Arrays.sort(users, new Comparator<User>() {
            @Override
            public int compare(User o1, User o2) {
                return o1.getName().compareTo(o2.getName());
            }
        });
        System.out.println(Arrays.toString(users));
    }

    @Test
    public  void customSort3(){
        User[] users = initData();
        //利用匿名内部提供了Comparator的实现类的匿名对象
        Arrays.sort(users, (o1,o2)->o1.getName().length() - o2.getName().length());
        System.out.println(Arrays.toString(users));
    }

    @Test
    public void stringSortByLength() {
        String[] arr = {"C++", "Java", "Web", "Spring Boot", "Python"};

        // 使用 Comparator 根据字符串长度排序
        Arrays.sort(arr, (s1, s2) -> s1.length() - s2.length());

        System.out.println(Arrays.toString(arr));
    }


}